package com.gw2.gw2world.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;

import com.gw2.gw2world.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.preference.PreferenceManager;
import android.view.WindowManager;

public class Tools {
	/** Convert a stream to String. It is mainly use after downloading JSON.
	 * @param inputStream The input stream
	 * @param contains Use to filter data but not implemented
	 * @return The text
	 * @throws IOException
	 */
	public static String convertStreamToString(InputStream inputStream, String...contains) throws IOException {
		if (inputStream != null) {
			InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader in = new BufferedReader(isr);
            String line;
            StringBuffer sb=new StringBuffer();
            while((line = in.readLine()) != null)
            	sb.append(line+"\n");
            in.close();
			return sb.toString();
		} else return "";
	}
	
	/** Force locale from preferences
	 * @param c Activity context
	 */
	public static void forceLocale(Context c) { //update locale: http://www.localwisdom.com/blog/2013/04/forcing-the-locale-in-an-android-app/
		final SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(c);
		Locale locale = new Locale(prefs.getString("language", "en"));
		Locale.setDefault(locale);
		Configuration config = c.getResources().getConfiguration(); config.locale = locale;
		c.getResources().updateConfiguration(config, c.getResources().getDisplayMetrics());
	}
	/** Check if the phone is USB connected
	 * @param context Activity context
	 * @return true if connected
	 */
	public static boolean isUsbConnected(Context context) { //http://stackoverflow.com/questions/8411846/android-usb-connection
        Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
    }
	/** Lock screen depending on shared preferences variables: screen_on and screen_on_usb
	 * @param a The Activity
	 */
	public static void lockScreenFromPreferences(Activity a) {
		final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(a);
		if(prefs.getBoolean("screen_on", false)) {
			if(prefs.getBoolean("screen_on_usb", false) && !isUsbConnected(a)) return;
			a.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
	}
	public static void unlockScreen(Activity a) {
		a.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}
	public static void lockScreen(Activity a) {
		a.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}
	/** Get the color from the state string in JSON
	 * @param c Activity context
	 * @param state The state (ie: Active, Inactive, Warmup, ...)
	 * @return The color number (0xAARRGGBB)
	 */
	public static int getColorFromState(Context c, String state) {
		if(state.equals("Inactive")) return c.getResources().getColor(R.color.event_inactive);
		else if(state.equals("Success")) return c.getResources().getColor(R.color.event_success);
		else if(state.equals("Fail")) return c.getResources().getColor(R.color.event_fail);
		else return c.getResources().getColor(R.color.event_active); //active/warmup/preparation
	}
	
	/** Play the notification sound from preference and vibrate if selected
	 * @param a The activity that is calling
	 */
	public static void notify(Activity a) {
		final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(a);
		if(prefs.getBoolean("notification", false)) {
			try {
				android.media.Ringtone r = android.media.RingtoneManager.getRingtone(a.getApplicationContext(), Uri.parse(prefs.getString("notification", "")));
				r.play();
				if(prefs.getBoolean("vibrate", false)) {
					android.os.Vibrator v = (android.os.Vibrator) a.getSystemService(Context.VIBRATOR_SERVICE);
					v.vibrate(400L);
				}
			} catch(Exception e) {
				
			}
		}
	}
	public static boolean isWifiEnabled(Activity a) {
		return ((WifiManager)a.getSystemService(Context.WIFI_SERVICE)).isWifiEnabled();
	}
	public static void enableWifi(Activity a) {
		((WifiManager)a.getSystemService(Context.WIFI_SERVICE)).setWifiEnabled(true);
	}
}
